<?php

namespace Api\Event;


/** 
 * 消息接口
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class MessageEvent extends BaseEvent 
{

	# ACTION

	/** 
	 * 发出信息数据
	 * @author Legend. <xcx_legender@qq.com>
	 * @param $type { comment, at, zan } ; $video_id, $uid, $to_users  array(to_uid)
	 * @return 
	 */
	// who to whom 
	public function send($type, $video_id, $uid, $to_users, $object_id = 0)
	{
		if ($uid > 0){
			$messModel = D('Common/Message');
			if (!is_array($to_users))
			{
				$to_users = array($to_users);
			}
			foreach ($to_users as $to_uid) {
				$messModel->send($type, $video_id, $uid, $to_uid, $object_id);
			}
		}
	}

	/** 
	 * 设置已读
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	//新增参数$filter 匹配的条件 susy<susy.liang@ilongyuan.com.cn>
	// 修改为合并条件 liubo 2016-07-12
	public function setRead($uid, $filter=array())
	{
		$messModel = D('Common/Message');

		$map = [
			'status' => $messModel::STATUS_UNREAD
		];
		$uid && $map['to'] = intval($uid);

		if (!empty($filter)) {
			$map = array_merge($map, $filter);
		}

		$messModel->where($map)->setField('status', $messModel::STATUS_READ);
	}


	# GET

	/** 
	 * 获取新消息条数
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	// 添加$types参数  liubo 2016-07-12
	public function getNewCount($uid, $types = [])
	{
		$messModel 	   = D('Common/Message');
		$map['status'] = $messModel::STATUS_UNREAD;
		$map['to']     = intval($uid);
		if (!empty($types)) {
			$map['type'] = ['in', $types];
		}
		return $messModel->where($map)->count();
	}


	/** 
	 * 获取相关target_id 列表
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function getTargetList($where, $limit)
	{
		$messModel = D('Common/Message');
		$ids = $messModel->field('DISTINCT target_id')->where($where)->limit($limit)->order('create_time desc')->select();
		foreach ($ids as $key => $value) {
			$data[] = $value['target_id'];
		}
		return $data;
	}

	/**
	*获取消息信息
	*返回信息有关联的视频， 最后一条消息的创建时间
	*@author susy<susy.liang@ilongyuan.com.cn>
	*@return array
	*/
	public function getMsgList($where, $limit){

		// $messModel = D('Common/Message');
		// $info = $messModel->field('target_id, create_time')->where($where)->group('target_id')->limit($limit)->order('status,create_time desc')->select();
		// if(!$info)
		// 	return false;

		// $ids = array();
		// foreach ($info as $key => $value) {
		// 	$ids[] = $value['target_id'];
		// }

		// $lastTime = $info[count($info)-1]['create_time'];

		// return array('ids'=>$ids, 'timestamp'=>$lastTime);

		$messModel = D('Common/Message');
		$lists = $messModel->where($where)->limit($limit)->order('status,create_time desc')->select();

		return $lists;
	}


}